package com.example.demo.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Goods;
import com.example.demo.entity.GoodsEntry;
import com.example.demo.entity.ResponseResult;
import com.example.demo.entity.Stock;
import com.example.demo.mapper.GoodsEntryMapper;
import com.example.demo.mapper.GoodsMapper;
import com.example.demo.mapper.StockMapper;
import com.example.demo.service.GoodsEntryService;
import com.example.demo.service.GoodsService;
import com.example.demo.service.StockService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.Arrays;
import java.util.List;

@Service
public class GoodsEntryServiceImpl extends ServiceImpl<GoodsEntryMapper, GoodsEntry>
    implements GoodsEntryService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private StockMapper stockMapper;


    @Override
    public ResponseResult getList() {
        List<GoodsEntry> goodsEntries = list();

        if(goodsEntries.isEmpty()){
            return ResponseResult.ok("没有入库单信息");
        }
        return ResponseResult.ok(goodsEntries);
    }

    @Override
    @Transactional // 因为关联到多个表了 所以使用事务来解决一下
    public ResponseResult saveGoodsEntry(GoodsEntry goodsEntry) {
        if(goodsEntry == null){
            return ResponseResult.fail("请输入有效的入库单信息");
        }
        /**
         * 首先这里插入之后  我们需要进行判断
         */
        boolean isSuccess = save(goodsEntry);

        if(!isSuccess){
            return ResponseResult.fail("录入失败");
        }
        /**
         * 对商品进行查询
         * 如果存在 那么需要增加数量  否则就是新增一条数据
         */
        String goodsName = goodsEntry.getGoodsName();
        List<Goods> goods = goodsMapper.selectList(new QueryWrapper<Goods>().eq("Goods_name", goodsName));
        /**
         * 如果本来就是存在  那么只需要更新库存
         */
        if(goods != null && goods.size() > 0){
            /**
             * 需要进行数量的更新
             */
            stockMapper.updateFromGoodsEntry(goodsEntry.getAmount(),goodsEntry.getGoodsName());
            return ResponseResult.ok("新增成功");
        }
        /**
         * 那么就需要添加到两个表
         */
        int isSuccess1 = goodsMapper.insert(new Goods(null, goodsName, "默认", goodsEntry.getSupplier(), "默认"));
        int insert = stockMapper.insert(new Stock(null, goodsName, goodsEntry.getAmount(), goodsEntry.getSupplier(), goodsEntry.getGoodsId(), DateTime.now().toSqlDate()));
        return ResponseResult.ok("新增成功");
    }
}
